﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Crank.Core
{
    public class FileLoadingLineProvider : ILineProvider
    {
        #region Blackboard Variables

        private static readonly IProperty<IList<string>> Files = Blackboard.Create<IList<string>>("Files");

        #endregion

        private TextReader reader;

        public FileLoadingLineProvider()
        {
            HasLines = true;
            LoadNextFile();
        }

        #region ILineProvider Members

        public bool HasLines
        {
            get; protected set;
        }

        public string GetNextLine()
        {
            return ReadNextLine();
        }

        private void LoadNextFile()
        {
            if (reader != null)
            {
                reader.Dispose();
                reader = null;
            }
            if (Files.Value != null && Files.Value.Count != 0)
            {
                string nextFile = Files.Value[0];
                Files.Value.RemoveAt(0);
                reader = new StreamReader(File.OpenRead(nextFile));
                return;
            }
        }

        private string ReadNextLine()
        {
            string line = null;
            if (reader == null)
                LoadNextFile();
            if (reader != null)
            {
                line = reader.ReadLine();
                if (line == null)
                {
                    LoadNextFile();
                    return ReadNextLine();
                }
            }
            if (line == null)
            {
                HasLines = false;
                line = String.Empty;
            }
            return line;
        }

        #endregion
    }
}
